package com.cqan.box.controller;

import static com.cqan.common.ViewName.*;

import java.util.List;
import java.util.StringTokenizer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.cqan.box.entity.Platform;
import com.cqan.box.service.PlatformService;
import com.cqan.controller.BaseController;
import com.cqan.exception.AppException;
import com.cqan.orm.PropertyFilter;
import com.google.common.collect.Lists;

@Controller
@RequestMapping("/platform")
public class PlatformController extends BaseController<Platform> {

	@Resource
	private PlatformService platformService;
	
	@RequestMapping(value="/list.htm")
	public ModelAndView list(Integer pageNo,HttpServletRequest request){
		ModelAndView mav = new ModelAndView(PLATFORM_LIST);
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(request);
		page.setPageNo(pageNo);
		page = platformService.search(page, filters);
		mav.addObject("page", page);
		return mav;
	}
	
	@RequestMapping(value="/edit.htm",method=RequestMethod.GET)
	public ModelAndView edit(Long id,Integer pageNo)throws AppException{
		ModelAndView mav = new ModelAndView(PLATFORM_EDIT);
		Platform platform = platformService.get(id);
		mav.addObject("platform", platform);
		mav.addObject("pageNo", pageNo);
		return mav;
	}
	
	
	@RequestMapping(value="/modify.htm",method=RequestMethod.POST)
	public ModelAndView modify(Long id,HttpServletRequest request)throws AppException{
		
		try {
			Platform b = platformService.get(id);
			Platform box = getRequestEntity(request);
			if (b!=null) {
					this.copyProperties(b, box);
					platformService.update(b);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new AppException();
		} 
		
		return   new ModelAndView(new RedirectView("list.htm?pageNo="+request.getParameter("pageNo")));
	}
	

	@ResponseBody
	@RequestMapping(value="/delete.htm")
	public String delete(String ids)throws AppException{
		try {
			if (ids!=null) {
				StringTokenizer st = new StringTokenizer(ids,"-");
				List<Long> list = Lists.newArrayList();
				while (st.hasMoreTokens()) {
					String id = st.nextToken();
					if (id!=null&&!"".equals(id)) {
						list.add(Long.parseLong(id));
					}
				}
				platformService.delete(list);
				return "删除成功！";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "该角色正在使用，暂时不能删除！";
		}
		return "参数异常！";
		
	}
}
